package com.twd.allcomponent.i18n.utils;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.*;

import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.security.Key;
import java.util.HashMap;
import java.util.Map;

/**
 * 生成jwt工具类
 */
public class JwtUtils {

    //定义对应的编码算法
    static SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
    //盐值
    static String secretKey = "d8de020f63754a9fa746ea74b831afc3sjksaksafjkaskfassfsfsdfsdfsdfsdfsdfsdfsd";

    //获取key（指定算法和盐值的key对象）
    private static Key generateKey(){
        //将盐值转成字节
        byte[] bytes = DatatypeConverter.parseBase64Binary(secretKey);
        //根据算法和盐值生成对应的key值
        Key key = new SecretKeySpec(bytes, signatureAlgorithm.getJcaName());
        return key;
    }

    /**
     * 将我们的数据使用JWT的方式变成一个token xxx.yyy.zzz
     * @param payLoad   负载（数据信息）
     * @return
     */
    public static String generatorToken(Map<String, String> payLoad){
        ObjectMapper objectMapper = new ObjectMapper();
        try{
            //构建jwt生成器
            JwtBuilder builder = Jwts.builder();
            //将负载信息设置到jwt生成器中
            JwtBuilder jwtBuilder = builder.setPayload(objectMapper.writeValueAsString(payLoad));
            //根据签名算法和key值，生成新的jwtBuilder
            JwtBuilder jwtBuilder1 = jwtBuilder.signWith(signatureAlgorithm, generateKey());
            String token = jwtBuilder1.compact();
            return token;
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 根据指定的token, 返回对应的body信息
     * @param token
     * @return
     */
    public static Claims phaseTokenGetBody(String token){
        JwtParser jwtParser = Jwts.parser().setSigningKey(generateKey());
        Jws<Claims> claimsJws = jwtParser.parseClaimsJws(token);
        Claims body = claimsJws.getBody();//主要存放的信息
        return body;
    }

    /**
     * 根据指定的token获取签名信息
     * @param token
     * @return
     */
    public static String phaseTokenGetSignature(String token){
        JwtParser jwtParser = Jwts.parser().setSigningKey(generateKey());
        Jws<Claims> claimsJws = jwtParser.parseClaimsJws(token);
        String signature = claimsJws.getSignature();
        return signature;
    }


    /**
     * 根据指定的token获取头信息
     * @param token
     * @return
     */
    public static JwsHeader phaseTokenGetHeader(String token){
        //获取解析器
        JwtParser parser = Jwts.parser();
        //设置签名key（盐值）
        parser = parser.setSigningKey(generateKey());
        //解析token
        Jws<Claims> claimsJws = parser.parseClaimsJws(token);
        JwsHeader header = claimsJws.getHeader();
        return header;
    }


    public static void main(String[] args) {
        //随机获取盐值
//        System.out.println(UUID.randomUUID().toString().replaceAll("-", ""));
        Map<String, String> payLoad = new HashMap<>();
        payLoad.put("name", "curry");
        String s = generatorToken(payLoad);
        //eyJhbGciOiJIUzI1NiJ9.eyJuYW1lIjoiY3VycnkifQ.Sf3GiF3p56nLzoAxEHLXcAckPmmPTtecj1_lGT9oV8s
        System.out.println(s);

        //调用自定义API获取结果
        Claims claims = phaseTokenGetBody(s);
        //{name=curry}
        System.out.println(claims);
    }

}


